<template>
  <div class="user-detail">
    <!-- 页面标题和返回按钮 -->
    <div class="d-flex justify-content-between align-items-center mb-4">
      <div class="page-header-content">
        <h2 class="page-title mb-1 animate-fade-in">用户详情</h2>
        <p class="text-muted mb-0 animate-fade-in-delay">查看和编辑用户详细信息</p>
      </div>
      <button class="btn btn-outline-secondary btn-hover-scale" @click="goBack">
        <i class="bi bi-arrow-left me-2"></i>返回用户列表
      </button>
    </div>

    <div class="row">
      <!-- 左侧内容区域 -->
      <div class="col-lg-8">
        <!-- 基本信息卡片 -->
        <div class="card mb-4 card-modern animate-slide-up" style="animation-delay: 0.1s">
          <div class="card-header bg-light d-flex align-items-center">
            <div class="card-icon-wrapper me-2">
              <i class="bi bi-person-vcard"></i>
            </div>
            <h5 class="card-title mb-0">基本信息</h5>
          </div>
          <div class="card-body">
            <div class="row">
              <div class="col-md-3 text-center mb-3 mb-md-0">
                <div class="avatar-container position-relative">
                  <img :src="user.avatar" alt="用户头像" class="user-avatar rounded-circle img-fluid border shadow-sm"
                    @error="handleImageError">
                  <div class="avatar-overlay">
                    <button class="btn btn-light btn-sm btn-change-avatar" @click="changeAvatar">
                      <i class="bi bi-camera"></i>
                    </button>
                  </div>
                </div>
                <div class="mt-3">
                  <button class="btn btn-outline-primary btn-sm btn-hover-scale" @click="changeAvatar">
                    <i class="bi bi-camera me-1"></i>更换头像
                  </button>
                </div>
              </div>
              <div class="col-md-9">
                <div class="row">
                  <div class="col-md-6 mb-3 form-group-animate">
                    <label class="form-label fw-bold text-muted small">用户ID</label>
                    <div class="form-control-plaintext fw-bold text-primary">{{ user.id || '-' }}</div>
                  </div>
                  <div class="col-md-6 mb-3 form-group-animate" style="animation-delay: 0.05s">
                    <label class="form-label fw-bold text-muted small">用户名</label>
                    <input type="text" class="form-control form-control-modern" v-model="user.username"
                      placeholder="请输入用户名">
                  </div>
                  <div class="col-md-6 mb-3 form-group-animate" style="animation-delay: 0.1s">
                    <label class="form-label fw-bold text-muted small">昵称</label>
                    <input type="text" class="form-control form-control-modern" v-model="user.nickname"
                      placeholder="请输入昵称">
                  </div>
                  <div class="col-md-6 mb-3 form-group-animate" style="animation-delay: 0.15s">
                    <label class="form-label fw-bold text-muted small">邮箱</label>
                    <input type="email" class="form-control form-control-modern" v-model="user.email"
                      placeholder="请输入邮箱">
                  </div>
                  <div class="col-md-6 mb-3 form-group-animate" style="animation-delay: 0.2s">
                    <label class="form-label fw-bold text-muted small">手机号</label>
                    <input type="text" class="form-control form-control-modern" v-model="user.phone"
                      placeholder="请输入手机号">
                  </div>
                  <div class="col-md-6 mb-3 form-group-animate" style="animation-delay: 0.25s">
                    <label class="form-label fw-bold text-muted small">学号</label>
                    <input type="text" class="form-control form-control-modern" v-model="user.studentId"
                      placeholder="请输入学号">
                  </div>
                  <div class="col-md-6 mb-3 form-group-animate" style="animation-delay: 0.25s">
                    <label class="form-label fw-bold text-muted small">密码</label>
                    <input type="text" class="form-control form-control-modern" v-model="user.password"
                      placeholder="密码">
                  </div>
                  <div class="col-12 mb-3 form-group-animate" style="animation-delay: 0.3s">
                    <label class="form-label fw-bold text-muted small">个人简介</label>
                    <textarea class="form-control form-control-modern" rows="3" v-model="user.bio"
                      placeholder="请输入个人简介"></textarea>
                    <div class="form-text text-end">{{ user.bio ? user.bio.length : 0 }}/500</div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- 用户状态信息卡片 -->
        <div class="card mb-4 card-modern animate-slide-up" style="animation-delay: 0.2s">
          <div class="card-header bg-light d-flex align-items-center">
            <div class="card-icon-wrapper me-2">
              <i class="bi bi-shield-check"></i>
            </div>
            <h5 class="card-title mb-0">账户状态</h5>
          </div>
          <div class="card-body">
            <div class="row">
              <div class="col-md-6 mb-3 form-group-animate">
                <label class="form-label fw-bold text-muted small">账号状态</label>
                <select class="form-select form-select-modern" v-model="user.status">
                  <option value="active">正常</option>
                  <option value="banned">禁用</option>
                  <option value="suspended">暂停</option>
                </select>
              </div>
              <div class="col-md-6 mb-3 form-group-animate" style="animation-delay: 0.05s">
                <label class="form-label fw-bold text-muted small">认证状态</label>
                <select class="form-select form-select-modern" v-model="user.isVerified">
                  <option :value="true">已认证</option>
                  <option :value="false">未认证</option>
                </select>
              </div>
              <div class="col-md-6 mb-3 form-group-animate" style="animation-delay: 0.1s">
                <label class="form-label fw-bold text-muted small">用户角色</label>
                <select class="form-select form-select-modern" v-model="user.role">
                  <option value="user">普通用户</option>
                  <option value="admin">管理员</option>
                </select>
              </div>

            </div>
          </div>
        </div>

        <!-- 操作按钮 -->
        <div class="d-flex justify-content-end gap-2 mt-2 animate-fade-in" style="animation-delay: 0.4s">
          <button class="btn btn-outline-secondary btn-hover-scale" @click="resetForm">
            <i class="bi bi-arrow-counterclockwise me-2"></i>重置
          </button>
          <button class="btn btn-primary btn-modern btn-hover-scale" @click="saveUser" :disabled="saving">
            <i class="bi bi-save me-2"></i>
            <span v-if="saving">
              <span class="spinner-border spinner-border-sm me-2" role="status"></span>
              保存中...
            </span>
            <span v-else>保存更改</span>
          </button>
        </div>

        <!-- 用户活动信息 -->
        <div class="card mb-4 card-modern animate-slide-up" style="animation-delay: 0.3s">
          <div class="card-header bg-light d-flex align-items-center">
            <div class="card-icon-wrapper me-2">
              <i class="bi bi-activity"></i>
            </div>
            <h5 class="card-title mb-0">用户活动</h5>
          </div>
          <div class="card-body">
            <ul class="nav nav-tabs mb-4 custom-tabs">
              <li class="nav-item">
                <a class="nav-link" :class="{ active: activeTab === 'posts' }" @click="activeTab = 'posts'" href="#">
                  <i class="bi bi-file-earmark-text me-1"></i>发布的帖子
                  <span class="badge bg-primary ms-1">{{ userPosts.length }}</span>
                </a>
              </li>
              <li class="nav-item">
                <a class="nav-link" :class="{ active: activeTab === 'likes' }" @click="activeTab = 'likes'" href="#">
                  <i class="bi bi-hand-thumbs-up me-1"></i>点赞的帖子
                  <span class="badge bg-primary ms-1">{{ userLikes.length }}</span>
                </a>
              </li>
              <li class="nav-item">
                <a class="nav-link" :class="{ active: activeTab === 'favorites' }" @click="activeTab = 'favorites'"
                  href="#">
                  <i class="bi bi-star me-1"></i>收藏的帖子
                  <span class="badge bg-primary ms-1">{{ userFavorites.length }}</span>
                </a>
              </li>
            </ul>

            <!-- 发布的帖子 -->
            <div v-if="activeTab === 'posts'" class="tab-content">
              <div v-if="userPosts.length === 0" class="text-center py-3">
                <i class="bi bi-file-earmark-text fs-1 text-muted"></i>
                <p class="mt-2 text-muted">该用户暂未发布任何帖子</p>
              </div>
              <div v-else class="row" style="max-height: 400px; overflow-y: auto;">
                <div v-for="(post, index) in userPosts" :key="post.id" class="col-md-6 mb-3 post-item"
                  :style="`animation-delay: ${index * 0.1}s`">
                  <div class="card h-100 shadow-sm post-card">
                    <img :src="post.cover" class="card-img-top post-cover" alt="帖子封面"
                      style="height: 120px; object-fit: cover;" @error="handlePostImageError">
                    <div class="card-body d-flex flex-column">
                      <h6 class="card-title text-truncate">{{ post.title }}</h6>
                      <p class="card-text flex-grow-1 small text-muted">
                        {{ post.summary || '暂无摘要' }}
                      </p>
                      <div class="d-flex justify-content-between text-muted small">
                        <span>{{ formatDate(post.createdAt) }}</span>
                        <span>{{ post.viewCount || 0 }} 浏览</span>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>

            <!-- 点赞的帖子 -->
            <div v-else-if="activeTab === 'likes'" class="tab-content">
              <div v-if="userLikes.length === 0" class="text-center py-3">
                <i class="bi bi-hand-thumbs-up fs-1 text-muted"></i>
                <p class="mt-2 text-muted">该用户暂未点赞任何帖子</p>
              </div>
              <div v-else class="row" style="max-height: 400px; overflow-y: auto;">
                <div v-for="(like, index) in userLikes" :key="like.id" class="col-md-6 mb-3 post-item"
                  :style="`animation-delay: ${index * 0.1}s`">
                  <div class="card h-100 shadow-sm post-card">
                    <img :src="like.cover" class="card-img-top post-cover" alt="帖子封面"
                      style="height: 120px; object-fit: cover;" @error="handlePostImageError">
                    <div class="card-body d-flex flex-column">
                      <h6 class="card-title text-truncate">{{ like.postTitle }}</h6>
                      <p class="card-text flex-grow-1 small text-muted">
                        发布人: {{ like.postAuthor }}
                      </p>
                      <div class="d-flex justify-content-between text-muted small">
                        <span>{{ formatDate(like.createdAt) }}</span>
                        <span>{{ like.views || 0 }} 浏览</span>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>

            <!-- 收藏的帖子 -->
            <div v-else-if="activeTab === 'favorites'" class="tab-content">
              <div v-if="userFavorites.length === 0" class="text-center py-3">
                <i class="bi bi-star fs-1 text-muted"></i>
                <p class="mt-2 text-muted">该用户暂未收藏任何帖子</p>
              </div>
              <div v-else class="row" style="max-height: 400px; overflow-y: auto;">
                <div v-for="(favorite, index) in userFavorites" :key="favorite.id" class="col-md-6 mb-3 post-item"
                  :style="`animation-delay: ${index * 0.1}s`">
                  <div class="card h-100 shadow-sm post-card">
                    <img :src="favorite.cover" class="card-img-top post-cover" alt="帖子封面"
                      style="height: 120px; object-fit: cover;" @error="handlePostImageError">
                    <div class="card-body d-flex flex-column">
                      <h6 class="card-title text-truncate">{{ favorite.postTitle }}</h6>
                      <p class="card-text flex-grow-1 small text-muted">
                        发布人: {{ favorite.postAuthor }}
                      </p>
                      <div class="d-flex justify-content-between text-muted small">
                        <span>{{ formatDate(favorite.createdAt) }}</span>
                        <span>{{ favorite.views || 0 }} 浏览</span>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 右侧信息面板 -->
      <div class="col-lg-4">
        <!-- 用户摘要卡片 -->
        <div class="card mb-4 card-modern animate-slide-up" style="animation-delay: 0.1s">
          <div class="card-header bg-light d-flex align-items-center">
            <div class="card-icon-wrapper me-2">
              <i class="bi bi-info-circle"></i>
            </div>
            <h5 class="card-title mb-0">用户摘要</h5>
          </div>
          <div class="card-body">
            <div class="text-center mb-3">
              <span :class="statusBadgeClass" class="badge me-2 badge-modern">{{ statusDisplayName }}</span>
              <span :class="roleBadgeClass" class="badge badge-modern">{{ roleDisplayName }}</span>
            </div>

            <div class="stats-container d-flex justify-content-around text-center mb-4">
              <div class="stat-item">
                <div class="stat-value">{{ followerCount }}</div>
                <div class="stat-label">粉丝</div>
              </div>
              <div class="stat-item">
                <div class="stat-value">{{ followingCount }}</div>
                <div class="stat-label">关注</div>
              </div>
            </div>

            <div class="row mb-3">
              <div class="col-6 mb-2">
                <div class="small text-muted">注册时间</div>
                <div class="fw-bold">{{ formatDate(user.createdAt) }}</div>
              </div>
              <div class="col-6 mb-2">
                <div class="small text-muted">最后更新</div>
                <div class="fw-bold">{{ formatDate(user.updatedAt) }}</div>
              </div>
            </div>
          </div>
        </div>

        <!-- 操作记录卡片 -->
        <div class="card mb-4 card-modern animate-slide-up" style="animation-delay: 0.2s">
          <div class="card-header bg-light d-flex align-items-center">
            <div class="card-icon-wrapper me-2">
              <i class="bi bi-clock-history"></i>
            </div>
            <h5 class="card-title mb-0">操作记录</h5>
          </div>
          <div class="card-body">
            <div class="d-flex align-items-center mb-3 pb-2 border-bottom">
              <div class="flex-shrink-0">
                <i class="bi bi-person-plus text-success fs-4"></i>
              </div>
              <div class="flex-grow-1 ms-3">
                <div class="fw-bold">账号创建</div>
                <div class="text-muted small">{{ formatDate(user.createdAt) }}</div>
              </div>
            </div>

            <div class="d-flex align-items-center mb-3 pb-2 border-bottom">
              <div class="flex-shrink-0">
                <i class="bi bi-pencil-square text-primary fs-4"></i>
              </div>
              <div class="flex-grow-1 ms-3">
                <div class="fw-bold">最后更新</div>
                <div class="text-muted small">{{ formatDate(user.updatedAt) }}</div>
              </div>
            </div>

          </div>
        </div>

        <!-- 关注列表 -->
        <div class="card mb-4 card-modern animate-slide-up" style="animation-delay: 0.3s">
          <div class="card-header bg-light d-flex justify-content-between align-items-center">
            <div class="d-flex align-items-center">
              <div class="card-icon-wrapper me-2">
                <i class="bi bi-person-plus"></i>
              </div>
              <h5 class="card-title mb-0">关注列表</h5>
            </div>
            <span class="badge bg-primary">{{ followingList.length }}</span>
          </div>
          <div class="card-body p-0">
            <div v-if="followingList.length === 0" class="text-center py-3">
              <p class="text-muted mb-0">暂无关注用户</p>
            </div>
            <div style="max-height: 250px; overflow-y: auto;">
              <ul v-if="followingList.length > 0" class="list-group list-group-flush">
                <li v-for="(following) in followingList.slice(0, 5)" :key="following.id"
                  class="list-group-item d-flex align-items-center">
                  <img :src="following.avatar" alt="头像" class="rounded-circle me-2" width="40" height="40"
                    @error="handleImageError">
                  <div class="flex-grow-1">
                    <div class="fw-bold">{{ following.nickname || following.username }}</div>
                    <div class="small text-muted">ID: {{ following.id }}</div>
                    <div class="small text-muted">{{ following.username }}</div>
                  </div>
                </li>
                <li v-if="followingList.length > 5" class="list-group-item text-center text-muted">
                  还有 {{ followingList.length - 5 }} 个关注...
                </li>
              </ul>
            </div>
          </div>
        </div>

        <!-- 粉丝列表 -->
        <div class="card card-modern animate-slide-up" style="animation-delay: 0.4s">
          <div class="card-header bg-light d-flex justify-content-between align-items-center">
            <div class="d-flex align-items-center">
              <div class="card-icon-wrapper me-2">
                <i class="bi bi-people"></i>
              </div>
              <h5 class="card-title mb-0">粉丝列表</h5>
            </div>
            <span class="badge bg-primary">{{ followerList.length }}</span>
          </div>
          <div class="card-body p-0">
            <div v-if="followerList.length === 0" class="text-center py-3">
              <p class="text-muted mb-0">暂无粉丝</p>
            </div>
            <div style="max-height: 250px; overflow-y: auto;">
              <ul v-if="followerList.length > 0" class="list-group list-group-flush">
                <li v-for="(follower) in followerList.slice(0, 5)" :key="follower.id"
                  class="list-group-item d-flex align-items-center">
                  <img :src="follower.avatar" alt="头像" class="rounded-circle me-2" width="40" height="40"
                    @error="handleImageError">
                  <div class="flex-grow-1">
                    <div class="fw-bold">{{ follower.nickname || follower.username }}</div>
                    <div class="small text-muted">ID: {{ follower.id }}</div>
                    <div class="small text-muted">{{ follower.username }}</div>
                  </div>
                </li>
                <li v-if="followerList.length > 5" class="list-group-item text-center text-muted">
                  还有 {{ followerList.length - 5 }} 个粉丝...
                </li>
              </ul>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { getUserInfoByIdService, 
          adminUpdateUserInfoService } from '@/api/user.js'
import { getFollowingListService, getFollowerListService } from '@/api/Follow.js'
import { getPostListNoPageService, 
          getPostDetailService, 
          getPostCoverByIdService } from '@/api/post.js'
import { getUserLikesService, 
          getUserFavoritesService } from '@/api/LikesFavorites.js'

// 默认图片
import defaultAvatar from '@/assets/images/头像加载失败.jpg'
import defaultPostCover from '@/assets/images/封面加载失败.webp'

// 路由相关
const route = useRoute()
const router = useRouter()

// 响应式数据
const user = ref({
  id: '',
  username: '',
  nickname: '',
  email: '',
  phone: '',
  studentId: '',
  bio: '',
  avatar: '',
  status: 'active',
  isVerified: false,
  role: 'user',
  lastLoginTime: null,
  createdAt: '',
  updatedAt: ''
})

const saving = ref(false)
const followingCount = ref(0)
const followerCount = ref(0)
const activeTab = ref('posts')
const userPosts = ref([])
const userLikes = ref([])
const userFavorites = ref([])
const followingList = ref([])
const followerList = ref([])

// 计算属性
const roleDisplayName = computed(() => {
  const roleMap = {
    'user': '普通用户',
    'admin': '管理员',
    'moderator': '版主'
  }
  return roleMap[user.value.role] || user.value.role
})

const statusDisplayName = computed(() => {
  const statusMap = {
    'active': '正常',
    'banned': '封禁',
    'suspended': '暂停'
  }
  return statusMap[user.value.status] || user.value.status
})

const statusBadgeClass = computed(() => {
  const statusClassMap = {
    'active': 'bg-success',
    'banned': 'bg-danger',
    'suspended': 'bg-warning text-dark'
  }
  return `badge ${statusClassMap[user.value.status] || 'bg-secondary'}`
})

const roleBadgeClass = computed(() => {
  const roleClassMap = {
    'user': 'bg-primary',
    'admin': 'bg-danger',
    'moderator': 'bg-info'
  }
  return `badge ${roleClassMap[user.value.role] || 'bg-secondary'}`
})

// 方法
const goBack = () => {
  router.push('/admin/users')
}

const handleImageError = (event) => {
  event.target.src = defaultAvatar
}

const handlePostImageError = (event) => {
  event.target.src = defaultPostCover
}

const changeAvatar = () => {
  ElMessage.info('更换头像功能待实现')
}

const formatDate = (dateString) => {
  if (!dateString) return '-'
  return new Date(dateString).toLocaleString('zh-CN')
}

// 加载用户信息
const loadUser = async () => {
  try {
    const userId = route.params.id
    const response = await getUserInfoByIdService(userId)
    if (response.code === 0) {
      user.value = { ...user.value, ...response.data }
      // 加载关注和粉丝数量
      loadFollowCounts(userId)
      // 加载用户活动数据
      loadUserActivity(userId)
      // 加载关注和粉丝列表
      loadFollowLists(userId)
    } else {
      ElMessage.error('获取用户信息失败: ' + response.msg)
    }
  } catch (error) {
    ElMessage.error('获取用户信息失败: ' + error.message)
  }
}

const loadFollowCounts = async (userId) => {
  try {
    // 获取关注数
    const followingResponse = await getFollowingListService(userId)
    if (followingResponse.code === 0) {
      followingCount.value = followingResponse.data.length
    }

    // 获取粉丝数
    const followerResponse = await getFollowerListService(userId)
    if (followerResponse.code === 0) {
      followerCount.value = followerResponse.data.length
    }
  } catch (error) {
    ElMessage.error('获取关注/粉丝信息失败: ' + error.message)
  }
}

const loadUserActivity = async (userId) => {
  try {
    // 获取用户发布的帖子
    const postsResponse = await getPostListNoPageService(userId)
    if (postsResponse.code === 0) {
      userPosts.value = await Promise.all(postsResponse.data.map(async (post) => {
        // 获取帖子封面
        const coverResponse = await getPostCoverByIdService(post.id)
        let cover = defaultPostCover

        if (coverResponse.code === 0 && coverResponse.data && coverResponse.data.length > 0) {
          const firstImage = coverResponse.data[0]
          cover = firstImage.imageUrl.startsWith('http')
            ? firstImage.imageUrl
            : `http://localhost:8080${firstImage.imageUrl}`
        }

        return {
          ...post,
          cover: cover,
          summary: post.content.length > 50 ? post.content.substring(0, 50) + '...' : post.content
        }
      }))
    }

    // 获取用户点赞的帖子
    const likesResponse = await getUserLikesService(userId, 'like')
    if (likesResponse.code === 0) {
      userLikes.value = await Promise.all(likesResponse.data.map(async (like) => {
        // 获取帖子详情
        const postResponse = await getPostDetailService(like.postId)
        // 获取帖子封面
        const coverResponse = await getPostCoverByIdService(like.postId)
        // 获取帖子作者信息
        const authorResponse = await getUserInfoByIdService(postResponse.data.userId)

        let cover = defaultPostCover
        if (coverResponse.code === 0 && coverResponse.data && coverResponse.data.length > 0) {
          const firstImage = coverResponse.data[0]
          cover = firstImage.imageUrl.startsWith('http')
            ? firstImage.imageUrl
            : `http://localhost:8080${firstImage.imageUrl}`
        }

        return {
          ...like,
          postTitle: postResponse.data.title,
          postAuthor: authorResponse.data.nickname || authorResponse.data.username || '未知用户',
          cover: cover,
          views: postResponse.data.viewCount || 0
        }
      }))
    }

    // 获取用户收藏的帖子
    const favoritesResponse = await getUserFavoritesService(userId, 'favorite')
    if (favoritesResponse.code === 0) {
      userFavorites.value = await Promise.all(favoritesResponse.data.map(async (favorite) => {
        // 获取帖子详情
        const postResponse = await getPostDetailService(favorite.postId)
        // 获取帖子封面
        const coverResponse = await getPostCoverByIdService(favorite.postId)
        // 获取帖子作者信息
        const authorResponse = await getUserInfoByIdService(postResponse.data.userId)

        let cover = defaultPostCover
        if (coverResponse.code === 0 && coverResponse.data && coverResponse.data.length > 0) {
          const firstImage = coverResponse.data[0]
          cover = firstImage.imageUrl.startsWith('http')
            ? firstImage.imageUrl
            : `http://localhost:8080${firstImage.imageUrl}`
        }

        return {
          ...favorite,
          postTitle: postResponse.data.title,
          postAuthor: authorResponse.data.nickname || authorResponse.data.username || '未知用户',
          cover: cover,
          views: postResponse.data.viewCount || 0
        }
      }))
    }
  } catch (error) {
    ElMessage.error('获取用户活动信息失败: ' + error.message)
  }
}

const loadFollowLists = async (userId) => {
  try {
    // 获取关注列表
    const followingResponse = await getFollowingListService(userId)
    if (followingResponse.code === 0) {
      // 获取每个关注用户的详细信息
      followingList.value = await Promise.all(followingResponse.data.map(async (following) => {
        try {
          const userInfoResponse = await getUserInfoByIdService(following.followingId)
          if (userInfoResponse.code === 0) {
            return {
              id: userInfoResponse.data.id,
              username: userInfoResponse.data.username,
              nickname: userInfoResponse.data.nickname,
              avatar: userInfoResponse.data.avatar || defaultAvatar
            }
          } else {
            // 如果获取详细信息失败，使用原始数据
            return {
              id: following.followingId,
              username: '未知用户',
              nickname: '未知用户',
              avatar: defaultAvatar
            }
          }
        } catch {
          // 如果请求失败，使用原始数据
          return {
            id: following.followingId,
            username: '未知用户',
            nickname: '未知用户',
            avatar: defaultAvatar
          }
        }
      }))
    }

    // 获取粉丝列表
    const followerResponse = await getFollowerListService(userId)
    if (followerResponse.code === 0) {
      // 获取每个粉丝用户的详细信息
      followerList.value = await Promise.all(followerResponse.data.map(async (follower) => {
        try {
          const userInfoResponse = await getUserInfoByIdService(follower.followerId)
          if (userInfoResponse.code === 0) {
            return {
              id: userInfoResponse.data.id,
              username: userInfoResponse.data.username,
              nickname: userInfoResponse.data.nickname,
              avatar: userInfoResponse.data.avatar || defaultAvatar
            }
          } else {
            // 如果获取详细信息失败，使用原始数据
            return {
              id: follower.followerId,
              username: '未知用户',
              nickname: '未知用户',
              avatar: defaultAvatar
            }
          }
        } catch {
          // 如果请求失败，使用原始数据
          return {
            id: follower.followerId,
            username: '未知用户',
            nickname: '未知用户',
            avatar: defaultAvatar
          }
        }
      }))
    }
  } catch (error) {
    ElMessage.error('获取关注/粉丝列表失败: ' + error.message)
  }
}

// 保存用户信息
const saveUser = async () => {
  saving.value = true
  try {
    // 创建一个不包含 avatar 字段的用户对象副本
    const userData = { ...user.value }
    delete userData.avatar
    
    const response = await adminUpdateUserInfoService(userData)
    if (response.code === 0) {
      ElMessage.success('用户信息更新成功')
    } else {
      ElMessage.error('更新用户信息失败: ' + response.msg)
    }
  } catch (error) {
    ElMessage.error('更新用户信息失败: ' + error.message)
  } finally {
    saving.value = false
  }
}

// 重置表单
const resetForm = () => {
  loadUser()
}


// 生命周期
onMounted(() => {
  loadUser()
})
</script>

<style scoped>
.page-title {
  color: #2c3e50;
  font-weight: 600;
}

/* 动画定义 */
@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(10px);
  }

  to {
    opacity: 1;
    transform: translateY(0);
  }
}

@keyframes slideUp {
  from {
    opacity: 0;
    transform: translateY(30px);
  }

  to {
    opacity: 1;
    transform: translateY(0);
  }
}

@keyframes bounceIn {
  0% {
    opacity: 0;
    transform: scale(0.3);
  }

  50% {
    opacity: 1;
    transform: scale(1.05);
  }

  70% {
    transform: scale(0.9);
  }

  100% {
    opacity: 1;
    transform: scale(1);
  }
}

/* 动画类 */
.animate-fade-in {
  animation: fadeIn 0.6s ease-out;
}

.animate-fade-in-delay {
  animation: fadeIn 0.6s ease-out 0.2s both;
}

.animate-slide-up {
  animation: slideUp 0.6s ease-out;
}

.animate-bounce-in {
  animation: bounceIn 0.6s ease-out;
}

/* 现代卡片样式 */
.card-modern {
  border: none;
  border-radius: 16px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  overflow: hidden;
}

.card-modern:hover {
  box-shadow: 0 8px 40px rgba(0, 0, 0, 0.12);
  transform: translateY(-2px);
}

.card-icon-wrapper {
  width: 32px;
  height: 32px;
  border-radius: 8px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
}

/* 头像样式优化 */
.avatar-container {
  display: inline-block;
  position: relative;
}

.user-avatar {
  width: 150px;
  height: 150px;
  object-fit: cover;
  transition: all 0.3s ease;
  border: 4px solid white;
  box-shadow: 0 8px 25px rgba(0, 0, 0, 0.15);
}

.avatar-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  opacity: 0;
  transition: all 0.3s ease;
}

.avatar-container:hover .avatar-overlay {
  opacity: 1;
}

.avatar-container:hover .user-avatar {
  transform: scale(1.05);
}

.btn-change-avatar {
  color: white;
  border: 2px solid white;
}

/* 表单样式优化 */
.form-control-modern,
.form-select-modern {
  border-radius: 12px;
  border: 2px solid #e9ecef;
  padding: 12px 16px;
  transition: all 0.3s ease;
  background: #fff;
}

.form-control-modern:focus,
.form-select-modern:focus {
  border-color: #667eea;
  box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
  transform: translateY(-1px);
}

.form-group-animate {
  animation: fadeIn 0.6s ease-out;
}

/* 按钮样式优化 */
.btn-hover-scale {
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
}

.btn-hover-scale:hover {
  transform: translateY(-2px) scale(1.02);
}

.btn-modern {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border: none;
  color: white;
  font-weight: 500;
  padding: 12px 24px;
}

/* 标签页样式优化 */
.custom-tabs .nav-link {
  border: none;
  border-radius: 8px;
  padding: 12px 20px;
  margin: 0 4px;
  color: #6c757d;
  transition: all 0.3s ease;
  position: relative;
  overflow: hidden;
}

.custom-tabs .nav-link::before {
  content: '';
  position: absolute;
  bottom: 0;
  left: 50%;
  width: 0;
  height: 3px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  transition: all 0.3s ease;
  transform: translateX(-50%);
}

.custom-tabs .nav-link.active::before {
  width: 100%;
}

.custom-tabs .nav-link.active {
  color: #667eea;
  background: rgba(102, 126, 234, 0.1);
}

/* 帖子卡片样式 */
.post-card {
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  cursor: pointer;
}

.post-card:hover {
  transform: translateY(-5px) scale(1.02);
}

.post-cover {
  height: 160px;
  object-fit: cover;
  transition: all 0.3s ease;
}

.card {
  border: none;
  border-radius: 12px;
  box-shadow: 0 0.125rem 0.25rem rgba(0, 0, 0, 0.075);
  transition: box-shadow 0.3s ease;
}

.card:hover {
  box-shadow: 0 0.5rem 1rem rgba(0, 0, 0, 0.15);
}

.card-header {
  background-color: #f8f9fa;
  border-bottom: 1px solid #e9ecef;
  border-top-left-radius: 12px !important;
  border-top-right-radius: 12px !important;
}

.form-label {
  font-weight: 500;
  color: #495057;
  margin-bottom: 0.25rem;
}

.form-control,
.form-select {
  border-radius: 8px;
  border: 1px solid #ced4da;
}

.form-control:focus,
.form-select:focus {
  border-color: #86b7fe;
  box-shadow: 0 0 0 0.25rem rgba(13, 110, 253, 0.25);
}

.form-control-plaintext {
  padding: 0.375rem 0;
}

.badge {
  font-size: 0.75rem;
  padding: 5px 12px;
  border-radius: 20px;
  font-weight: 500;
}

.btn {
  border-radius: 8px;
}

.text-muted.small {
  font-size: 0.75rem;
}

.nav-tabs .nav-link {
  cursor: pointer;
  border: none;
  background-color: transparent;
  transition: all 0.3s ease;
}

.nav-tabs .nav-link:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}

.nav-tabs .nav-link.active {
  border-bottom: 2px solid #0d6efd;
  font-weight: 500;
}

.list-group-item {
  border: none;
  border-bottom: 1px solid #eee;
}

.list-group-item:last-child {
  border-bottom: none;
}

.text-truncate {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

/* 统计数字样式 */
.stats-container {
  display: flex;
  justify-content: space-around;
  text-align: center;
}

.stat-item {
  padding: 0 20px;
}

.stat-value {
  font-size: 2rem;
  font-weight: 700;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  -webkit-background-clip: text;
  background-clip: border-box;
  -webkit-text-fill-color: transparent;
}

.stat-label {
  font-size: 0.875rem;
  color: #6c757d;
  margin-top: 4px;
}

/* 徽章样式 */
.badge-modern {
  padding: 8px 16px;
  border-radius: 20px;
  font-weight: 500;
  font-size: 0.75rem;
}

/* 响应式优化 */
@media (max-width: 768px) {
  .card-modern {
    border-radius: 12px;
    margin-bottom: 1rem;
  }

  .stats-container {
    flex-direction: column;
    gap: 1rem;
  }

  .user-avatar {
    width: 120px;
    height: 120px;
  }
}
</style>